package com.rainszj.controller.site;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rainszj.pojo.vo.DetailedBlog;
import com.rainszj.pojo.vo.IndexBlog;
import com.rainszj.service.BlogService;
import com.rainszj.service.TagService;
import com.rainszj.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import static com.rainszj.constant.WebConstant.*;

/**
 * @author rainszj
 * 2020/3/16
 */
@Slf4j
@Controller
public class HomeController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    /**
     * 跳转到网站的首页
     *
     * @param pageNum
     * @param model
     * @return
     */
    @GetMapping({"/", "/index.html", "index"})
    public String toIndexPage(@RequestParam(defaultValue = "1", name = "pageNum") Integer pageNum,
                              Model model) {
        PageInfo<IndexBlog> pageInfo = PageHelper.startPage(pageNum, PAGE_SIZE).doSelectPageInfo(() -> blogService.listIndexBlog());

        model.addAttribute("latestBlog", blogService.listLatestBlog(LATEST_ARTICLE_AMOUNT));
        model.addAttribute("types", typeService.listAllType());
        model.addAttribute("tags", tagService.listAllTag());
        model.addAttribute("pageInfo", pageInfo);

        int size = tagService.listAllTag().get(0).getBlogs().size();
        log.info(size+"");

        return "site/index";
    }

    /**
     * 跳转到相应的文章
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/article/{id}")
    public String showArticleById(@PathVariable("id") Long id, Model model) {
        DetailedBlog detailedBlog = blogService.getDetailedBlogById(id);
        model.addAttribute("detailedBlog", detailedBlog);

        return "site/blog";
    }

    @GetMapping("/search/{item}")
    public String toQuery(@PathVariable(name = "item") final String item,
                               Model model) {
        PageInfo<IndexBlog> pageInfo = null;
        // 查询条件为空
        if (!"".equals(item)) {
            pageInfo = PageHelper.startPage(1, PAGE_SIZE).doSelectPageInfo(() -> blogService.queryBlogByString(item));
        }
        // 查询没有结果
        if (pageInfo.getTotal() == 0){
            pageInfo = null;
        }

        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("queryStr", item);
        return "site/search";
    }

    @GetMapping("/search")
    public String toQuery() {
        return "site/search";
    }


    @GetMapping("/footerBlog")
    public String loadFooterBlog(Model model) {

        model.addAttribute("footerBlogList", blogService.listLatestBlog(FOOTER_ARTICLE_AMOUNT));
        return "commons/common :: footerBlogList";
    }


}
